<template>
  <div class="favorites-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>收藏管理</span>
          <el-button type="primary" @click="loadFavorites">刷新</el-button>
        </div>
      </template>

      <!-- 搜索筛选 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户ID">
          <el-input
            v-model="searchForm.userId"
            placeholder="请输入用户ID"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item label="图片ID">
          <el-input
            v-model="searchForm.imageId"
            placeholder="请输入图片ID"
            clearable
            @clear="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计信息 -->
      <el-row :gutter="20" class="stats-row" v-if="stats">
        <el-col :span="6">
          <el-statistic title="总收藏数" :value="stats.total" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="今日新增" :value="stats.today" />
        </el-col>
      </el-row>

      <!-- 收藏列表 -->
      <el-table
        v-loading="loading"
        :data="favoritesList"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="userId" label="用户ID" width="200" />
        <el-table-column prop="imageId" label="图片ID" width="100" />
        <el-table-column label="图片" width="120">
          <template #default="{ row }">
            <el-image
              :src="row.imageThumbnail || row.imageUrl"
              :preview-src-list="[row.imageUrl]"
              fit="cover"
              style="width: 80px; height: 80px"
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column prop="imageTitle" label="图片标题" min-width="150" show-overflow-tooltip />
        <el-table-column prop="createdAt" label="收藏时间" width="180" />
        <el-table-column label="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const loading = ref(false)
const favoritesList = ref([])
const stats = ref(null)

const searchForm = ref({
  userId: '',
  imageId: ''
})

const pagination = ref({
  page: 1,
  pageSize: 20,
  total: 0
})

// 加载收藏列表
async function loadFavorites() {
  loading.value = true
  try {
    const params = {
      page: pagination.value.page,
      pageSize: pagination.value.pageSize
    }
    
    if (searchForm.value.userId) {
      params.userId = searchForm.value.userId
    }
    
    if (searchForm.value.imageId) {
      params.imageId = searchForm.value.imageId
    }
    
    const res = await request.get('/favorites', { params })
    
    favoritesList.value = res.list || []
    pagination.value.total = res.total || 0
    
    // 加载统计信息
    loadStats()
  } catch (error) {
    ElMessage.error(error.message || '加载失败')
  } finally {
    loading.value = false
  }
}

// 加载统计信息
async function loadStats() {
  try {
    const res = await request.get('/favorites/stats')
    stats.value = res
  } catch (error) {
    console.error('加载统计信息失败:', error)
  }
}

// 搜索
function handleSearch() {
  pagination.value.page = 1
  loadFavorites()
}

// 重置
function handleReset() {
  searchForm.value = {
    userId: '',
    imageId: ''
  }
  handleSearch()
}

// 删除收藏
function handleDelete(row) {
  ElMessageBox.confirm(
    `确定要删除用户 ${row.userId} 对图片 ${row.imageId} 的收藏吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request.delete(`/favorites/${row.id}`)
      ElMessage.success('删除成功')
      loadFavorites()
    } catch (error) {
      ElMessage.error(error.message || '删除失败')
    }
  }).catch(() => {
    // 用户取消
  })
}

// 分页大小改变
function handleSizeChange(size) {
  pagination.value.pageSize = size
  pagination.value.page = 1
  loadFavorites()
}

// 页码改变
function handlePageChange(page) {
  pagination.value.page = page
  loadFavorites()
}

onMounted(() => {
  loadFavorites()
})
</script>

<style scoped>
.favorites-container {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.stats-row {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
</style>

